<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="platformOrderNo">
        <el-input
            v-model="queryParams.platformOrderNo"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="invoiceNumber">
        <el-input
            v-model="queryParams.invoiceNumber"
            placeholder="请输入发货单号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="contractTele">
        <el-input
            v-model="queryParams.contractTele"
            placeholder="请输入联系人电话"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="orderCreateTime">
        <el-date-picker clearable
                        v-model="queryParams.orderCreateTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择订单创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['order:platform:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-tabs class="demo-tabs" v-model="activeName" @tab-change="handleTabChange">
      <el-tab-pane label="全部订单" name="first">
        <el-table v-loading="loading" :data="platformList" row-key="orderId" @row-click="handleRowClick" @expand-change="handleExpandChange"
                  :row-class-name="getPlatformRowClassName" size="small" border>
          <el-table-column type="expand" width="55" align="center">
            <!--  等用商品接口把商品信息展示到这个插槽的地方  -->
            <template #default="scope">
              <div class="expand-wrapper" v-loading="expandLoading[scope.row.orderId] === true">
                <el-table v-if="Array.isArray(scope.row.goodDetils) && scope.row.goodDetils.length" :data="scope.row.goodDetils">
                  <el-table-column label="商品主图" align="center">
                    <template #default="g">
                      <div class="goods-image">
                        <el-image :src="g.row.goodsImage || '/default-product.png'" fit="cover"
                                  :preview-src-list="(g.row.goodsImage ) ? [g.row.goodsImage || g.row.image] : []" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品名称" align="center">
                    <template #default="g">{{ g.row.goodsName || g.row.goodName || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品规格" align="center">
                    <template #default="g">{{ g.row.goodSize || g.row.spec || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品单价" align="center">
                    <template #default="g">{{ g.row.goodsPrice ?? g.row.price ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="购买数量" align="center">
                    <template #default="g">{{ g.row.count ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="小计" align="center">
                    <template #default="g">{{ g.row.realPrice ?? '-' }}</template>
                  </el-table-column>
                </el-table>
                <el-empty v-else description="暂无商品" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="center" prop="platformOrderNo"/>
          <el-table-column label="订单描述" align="center" prop="platformOrderDesc"/>
          <el-table-column label="商品数量" align="center" prop="count" width="80px"/>
          <el-table-column label="商品总额" align="center" prop="platformOrderPrice" width="80px"/>
          <el-table-column label="优惠券" align="center" prop="couponsId"/>
          <el-table-column label="实付价格" align="center" prop="realPrice" width="80px"/>
          <el-table-column label="货源地" align="center" prop="sourcesAddress"/>
          <el-table-column label="发货单号" align="center" prop="invoiceNumber"/>
          <el-table-column label="联系人姓名" align="center" prop="contactName" width="100px"/>
          <el-table-column label="联系人电话" align="center" prop="contractTele"/>
          <el-table-column label="联系人地址" align="center" prop="contractAddress"/>
          <el-table-column label="订单状态" align="center" prop="status" width="80px">
            <template #default="scope">
              {{ getOrderStatusText(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                         v-hasPermi="['order:platform:edit']">详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-tab-pane>
      <el-tab-pane label="待发货订单" name="second">
        <el-table v-loading="loading" :data="notShippedList" row-key="orderId" @row-click="handleNotShippedRowClick" @expand-change="handleExpandChange"
                  :row-class-name="getNotShippedRowClassName" size="small" border>
          <el-table-column type="expand" width="55" align="center">
            <!--  等用商品接口把商品信息展示到这个插槽的地方  -->
            <template #default="scope">
              <div class="expand-wrapper" v-loading="expandLoading[scope.row.orderId] === true">
                <el-table v-if="Array.isArray(scope.row.goodDetils) && scope.row.goodDetils.length" :data="scope.row.goodDetils">
                  <el-table-column label="商品主图" align="center">
                    <template #default="g">
                      <div class="goods-image">
                        <el-image :src="(g.row.goodsImage || g.row.image) || '/default-product.png'" fit="cover"
                                  :preview-src-list="(g.row.goodsImage || g.row.image) ? [g.row.goodsImage || g.row.image] : []" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品名称" align="center">
                    <template #default="g">{{ g.row.goodsName || g.row.goodName || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品规格" align="center">
                    <template #default="g">{{ g.row.goodSize || g.row.spec || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品单价" align="center">
                    <template #default="g">{{ g.row.goodsPrice ?? g.row.price ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="购买数量" align="center">
                    <template #default="g">{{ g.row.count ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="小计" align="center">
                    <template #default="g">{{ g.row.realPrice ?? '-' }}</template>
                  </el-table-column>
                </el-table>
                <el-empty v-else description="暂无商品" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="center" prop="platformOrderNo"/>
          <el-table-column label="订单描述" align="center" prop="platformOrderDesc"/>
          <el-table-column label="商品数量" align="center" prop="count" width="80px"/>
          <el-table-column label="商品总额" align="center" prop="platformOrderPrice" width="80px"/>
          <el-table-column label="优惠券" align="center" prop="couponsId"/>
          <el-table-column label="实付价格" align="center" prop="realPrice" width="80px"/>
          <el-table-column label="货源地" align="center" prop="sourcesAddress"/>
          <el-table-column label="发货单号" align="center" prop="invoiceNumber"/>
          <el-table-column label="联系人姓名" align="center" prop="contactName" width="100px"/>
          <el-table-column label="联系人电话" align="center" prop="contractTele"/>
          <el-table-column label="联系人地址" align="center" prop="contractAddress"/>
          <el-table-column label="订单状态" align="center" prop="status" width="80px">
            <template #default="scope">
              {{ getOrderStatusText(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px">
            <template #default="scope">
              <el-button link type="primary" plain @click="handleUpdate(scope.row)"
                         v-hasPermi="['order:platform:edit']">发货
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="已发货订单" name="third">
        <el-table v-loading="loading" :data="shippedList" row-key="orderId" @row-click="handleShippedRowClick" @expand-change="handleExpandChange"
                  :row-class-name="getShippedRowClassName" size="small" border>
          <el-table-column type="expand" width="55" align="center">
            <!--  等用商品接口把商品信息展示到这个插槽的地方  -->
            <template #default="scope">
              <div class="expand-wrapper" v-loading="expandLoading[scope.row.orderId] === true">
                <el-table v-if="Array.isArray(scope.row.goodDetils) && scope.row.goodDetils.length" :data="scope.row.goodDetils">
                  <el-table-column label="商品主图" align="center">
                    <template #default="g">
                      <div class="goods-image">
                        <el-image :src="(g.row.goodsImage || g.row.image) || '/default-product.png'" fit="cover"
                                  :preview-src-list="(g.row.goodsImage || g.row.image) ? [g.row.goodsImage || g.row.image] : []" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品名称" align="center">
                    <template #default="g">{{ g.row.goodsName || g.row.goodName || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品规格" align="center">
                    <template #default="g">{{ g.row.goodSize || g.row.spec || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品单价" align="center">
                    <template #default="g">{{ g.row.goodsPrice ?? g.row.price ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="购买数量" align="center">
                    <template #default="g">{{ g.row.count ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="小计" align="center">
                    <template #default="g">{{ g.row.realPrice ?? '-' }}</template>
                  </el-table-column>
                </el-table>
                <el-empty v-else description="暂无商品" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="center" prop="platformOrderNo"/>
          <el-table-column label="订单描述" align="center" prop="platformOrderDesc"/>
          <el-table-column label="商品数量" align="center" prop="count" width="80px"/>
          <el-table-column label="商品总额" align="center" prop="platformOrderPrice" width="80px"/>
          <el-table-column label="优惠券" align="center" prop="couponsId"/>
          <el-table-column label="实付价格" align="center" prop="realPrice" width="80px"/>
          <el-table-column label="货源地" align="center" prop="sourcesAddress"/>
          <el-table-column label="发货单号" align="center" prop="invoiceNumber"/>
          <el-table-column label="联系人姓名" align="center" prop="contactName" width="100px"/>
          <el-table-column label="联系人电话" align="center" prop="contractTele"/>
          <el-table-column label="联系人地址" align="center" prop="contractAddress"/>
          <el-table-column label="订单状态" align="center" prop="status" width="80px">
            <template #default="scope">
              {{ getOrderStatusText(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                         v-hasPermi="['order:platform:edit']">详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="已完成订单" name="fourth">
        <el-table v-loading="loading" :data="completedList" row-key="orderId" @row-click="handleCompletedRowClick" @expand-change="handleExpandChange"
                  :row-class-name="getCompletedRowClassName" size="small" border>
          <el-table-column type="expand" width="55" align="center">
            <!--  等用商品接口把商品信息展示到这个插槽的地方  -->
            <template #default="scope">
              <div class="expand-wrapper" v-loading="expandLoading[scope.row.orderId] === true">
                <el-table v-if="Array.isArray(scope.row.goodDetils) && scope.row.goodDetils.length" :data="scope.row.goodDetils">
                  <el-table-column label="商品主图" align="center">
                    <template #default="g">
                      <div class="goods-image">
                        <el-image :src="(g.row.goodsImage || g.row.image) || '/default-product.png'" fit="cover"
                                  :preview-src-list="(g.row.goodsImage || g.row.image) ? [g.row.goodsImage || g.row.image] : []" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品名称" align="center">
                    <template #default="g">{{ g.row.goodsName || g.row.goodName || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品规格" align="center">
                    <template #default="g">{{ g.row.goodSize || g.row.spec || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品单价" align="center">
                    <template #default="g">{{ g.row.goodsPrice ?? g.row.price ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="购买数量" align="center">
                    <template #default="g">{{ g.row.count ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="小计" align="center">
                    <template #default="g">{{ g.row.realPrice ?? '-' }}</template>
                  </el-table-column>
                </el-table>
                <el-empty v-else description="暂无商品" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="center" prop="platformOrderNo"/>
          <el-table-column label="订单描述" align="center" prop="platformOrderDesc"/>
          <el-table-column label="商品数量" align="center" prop="count" width="80px"/>
          <el-table-column label="商品总额" align="center" prop="platformOrderPrice" width="80px"/>
          <el-table-column label="优惠券" align="center" prop="couponsId"/>
          <el-table-column label="实付价格" align="center" prop="realPrice" width="80px"/>
          <el-table-column label="货源地" align="center" prop="sourcesAddress"/>
          <el-table-column label="发货单号" align="center" prop="invoiceNumber"/>
          <el-table-column label="联系人姓名" align="center" prop="contactName" width="100px"/>
          <el-table-column label="联系人电话" align="center" prop="contractTele"/>
          <el-table-column label="联系人地址" align="center" prop="contractAddress"/>
          <el-table-column label="订单状态" align="center" prop="status" width="80px">
            <template #default="scope">
              {{ getOrderStatusText(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                         v-hasPermi="['order:platform:edit']">详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="未支付订单" name="fifth">
        <el-table v-loading="loading" :data="unpaidList" row-key="orderId" @row-click="handleUnpaidRowClick" @expand-change="handleExpandChange"
                  :row-class-name="getUnpaidRowClassName" size="small" border>
          <el-table-column type="expand" width="55" align="center">
            <!--  等用商品接口把商品信息展示到这个插槽的地方  -->
            <template #default="scope">
              <div class="expand-wrapper" v-loading="expandLoading[scope.row.orderId] === true">
                <el-table v-if="Array.isArray(scope.row.goodDetils) && scope.row.goodDetils.length" :data="scope.row.goodDetils">
                  <el-table-column label="商品主图" align="center">
                    <template #default="g">
                      <div class="goods-image">
                        <el-image :src="(g.row.goodsImage || g.row.image) || '/default-product.png'" fit="cover"
                                  :preview-src-list="(g.row.goodsImage || g.row.image) ? [g.row.goodsImage || g.row.image] : []" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品名称" align="center">
                    <template #default="g">{{ g.row.goodsName || g.row.goodName || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品规格" align="center">
                    <template #default="g">{{ g.row.goodSize || g.row.spec || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品单价" align="center">
                    <template #default="g">{{ g.row.goodsPrice ?? g.row.price ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="购买数量" align="center">
                    <template #default="g">{{ g.row.count ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="小计" align="center">
                    <template #default="g">{{ g.row.realPrice ?? '-' }}</template>
                  </el-table-column>
                </el-table>
                <el-empty v-else description="暂无商品" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="center" prop="platformOrderNo"/>
          <el-table-column label="订单描述" align="center" prop="platformOrderDesc"/>
          <el-table-column label="商品数量" align="center" prop="count" width="80px"/>
          <el-table-column label="商品总额" align="center" prop="platformOrderPrice" width="80px"/>
          <el-table-column label="优惠券" align="center" prop="couponsId"/>
          <el-table-column label="实付价格" align="center" prop="realPrice" width="80px"/>
          <el-table-column label="货源地" align="center" prop="sourcesAddress"/>
          <el-table-column label="发货单号" align="center" prop="invoiceNumber"/>
          <el-table-column label="联系人姓名" align="center" prop="contactName" width="100px"/>
          <el-table-column label="联系人电话" align="center" prop="contractTele"/>
          <el-table-column label="联系人地址" align="center" prop="contractAddress"/>
          <el-table-column label="订单状态" align="center" prop="status" width="80px">
            <template #default="scope">
              {{ getOrderStatusText(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                         v-hasPermi="['order:platform:edit']">详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="已取消订单" name="sixth">
        <el-table v-loading="loading" :data="canceledList" row-key="orderId" @row-click="handleCanceledRowClick" @expand-change="handleExpandChange"
                  :row-class-name="getCanceledRowClassName" size="small" border>
          <el-table-column type="expand" width="55" align="center">
            <!--  等用商品接口把商品信息展示到这个插槽的地方  -->
            <template #default="scope">
              <div class="expand-wrapper" v-loading="expandLoading[scope.row.orderId] === true">
                <el-table v-if="Array.isArray(scope.row.goodDetils) && scope.row.goodDetils.length" :data="scope.row.goodDetils">
                  <el-table-column label="商品主图" align="center">
                    <template #default="g">
                      <div class="goods-image">
                        <el-image :src="(g.row.goodsImage || g.row.image) || '/default-product.png'" fit="cover"
                                  :preview-src-list="(g.row.goodsImage || g.row.image) ? [g.row.goodsImage || g.row.image] : []" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品名称" align="center">
                    <template #default="g">{{ g.row.goodsName || g.row.goodName || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品规格" align="center">
                    <template #default="g">{{ g.row.goodSize || g.row.spec || '-' }}</template>
                  </el-table-column>
                  <el-table-column label="商品单价" align="center">
                    <template #default="g">{{ g.row.goodsPrice ?? g.row.price ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="购买数量" align="center">
                    <template #default="g">{{ g.row.count ?? '-' }}</template>
                  </el-table-column>
                  <el-table-column label="小计" align="center">
                    <template #default="g">{{ g.row.realPrice ?? '-' }}</template>
                  </el-table-column>
                </el-table>
                <el-empty v-else description="暂无商品" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="center" prop="platformOrderNo"/>
          <el-table-column label="订单描述" align="center" prop="platformOrderDesc"/>
          <el-table-column label="商品数量" align="center" prop="count" width="80px"/>
          <el-table-column label="商品总额" align="center" prop="platformOrderPrice" width="80px"/>
          <el-table-column label="优惠券" align="center" prop="couponsId"/>
          <el-table-column label="实付价格" align="center" prop="realPrice" width="80px"/>
          <el-table-column label="货源地" align="center" prop="sourcesAddress"/>
          <el-table-column label="发货单号" align="center" prop="invoiceNumber"/>
          <el-table-column label="联系人姓名" align="center" prop="contactName" width="100px"/>
          <el-table-column label="联系人电话" align="center" prop="contractTele"/>
          <el-table-column label="联系人地址" align="center" prop="contractAddress"/>
          <el-table-column label="订单状态" align="center" prop="status" width="80px">
            <template #default="scope">
              {{ getOrderStatusText(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                         v-hasPermi="['order:platform:edit']">详情
              </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)"
                         v-hasPermi="['order:platform:remove']">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

  </div>
</template>

<script setup name="Platform">
import {listPlatform, getPlatform, delPlatform, addPlatform, updatePlatform} from "@/api/order/platform"
import {useRouter} from "vue-router";
import {listGoodsByShopId} from "@/api/order/goods.js";

const {proxy} = getCurrentInstance()
const router = useRouter()
const platformList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const activeName = ref('first')
// 每行展开时按需获取对应订单的商品明细，避免全部展示

// 各个tab页面的选中数据（单选）
const selectedPlatformRow = ref(null)
const selectedNotShippedRow = ref(null)
const selectedShippedRow = ref(null)
const selectedCompletedRow = ref(null)
const selectedUnpaidRow = ref(null)
const selectedCanceledRow = ref(null)

// 各个tab页面的选中行ID（单选）
const selectedPlatformId = ref(null)
const selectedNotShippedId = ref(null)
const selectedShippedId = ref(null)
const selectedCompletedId = ref(null)
const selectedUnpaidId = ref(null)
const selectedCanceledId = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    platformOrderNo: null,
    platformOrderDesc: null,
    platformOrderPrice: null,
    realPrice: null,
    count: null,
    sourcesAddress: null,
    invoiceNumber: null,
    couponsId: null,
    contactName: null,
    contractTele: null,
    contractAddress: null,
    payType: null,
    payTime: null,
    orderEndTime: null,
    status: null,
    orderCreateTime: null,
    orderCompleteTime: null,
    isPrinted: null,
    isAfterSales: null,
    isEvaluate: null,
    goodPrice: null
  },
  rules: {
    platformOrderNo: [
      {required: true, message: "订单编号不能为空", trigger: "blur"}
    ],
    platformOrderPrice: [
      {required: true, message: "商品单价不能为空", trigger: "blur"}
    ],
    realPrice: [
      {required: true, message: "实付价格不能为空", trigger: "blur"}
    ],
    count: [
      {required: true, message: "购买的商品数量不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "订单状态不能为空", trigger: "change"}
    ],
    isAfterSales: [
      {required: true, message: "是否售后不能为空", trigger: "blur"}
    ],
    isEvaluate: [
      {required: true, message: "是否评价不能为空", trigger: "blur"}
    ],
  }
})

const {queryParams, form, rules} = toRefs(data)

// 订单状态转换函数
function getOrderStatusText(status) {
  const statusMap = {
    1: '待支付',
    2: '待发货',
    3: '已发货',
    4: '已完成',
    5: '已取消',
    6: '售后处理'
  };
  return statusMap[status] || '未知状态';
}

const unpaidList = ref([])
const canceledList = ref([])
const completedList = ref([])
const notShippedList = ref([])
const shippedList = ref([])
// 每个订单展开的加载状态
const expandLoading = reactive({})

/** 查询订单列表列表 */
function getList() {
  loading.value = true
  listPlatform(queryParams.value).then(response => {
    platformList.value = response.rows
    unpaidList.value = response.rows.filter(item => item.status === 1)
    notShippedList.value = response.rows.filter(item => item.status === 2)
    shippedList.value = response.rows.filter(item => item.status === 3)
    completedList.value = response.rows.filter(item => item.status === 4)
    canceledList.value = response.rows.filter(item => item.status === 5)
    total.value = response.total
    loading.value = false
  })
}


// 表单重置
function reset() {
  form.value = {
    orderId: null,
    platformOrderNo: null,
    platformOrderDesc: null,
    platformOrderPrice: null,
    realPrice: null,
    count: null,
    sourcesAddress: null,
    invoiceNumber: null,
    remark: null,
    couponsId: null,
    contactName: null,
    contractTele: null,
    contractAddress: null,
    payType: null,
    payTime: null,
    orderEndTime: null,
    status: null,
    orderCreateTime: null,
    orderCompleteTime: null,
    isPrinted: null,
    isAfterSales: null,
    isEvaluate: null,
    goodPrice: null
  }
  proxy.resetForm("platformRef")
}

// 行展开时，懒加载当前订单的商品明细
function handleExpandChange(row) {
  if (!row) return
  // 已有明细则不再请求
  if (Array.isArray(row.goodDetils) && row.goodDetils.length > 0) return
  const orderId = row.orderId
  if (!orderId) return
  expandLoading[orderId] = true
  
  // 获取平台上所有商品信息
  listGoodsByShopId(0).then(response => {
    const allGoods = response?.rows || []
    
    // 根据订单描述或商品名称匹配对应的商品
    let matchedGoods = []
    if (row.platformOrderDesc) {
      // 尝试通过订单描述匹配商品
      matchedGoods = allGoods.filter(good => 
        good.goodsName && good.goodsName.includes(row.platformOrderDesc) ||
        good.goodName && good.goodName.includes(row.platformOrderDesc)
      )
    }
    
    // 如果没有匹配到商品，使用订单基本信息构造商品数据
    if (matchedGoods.length === 0) {
      row.goodDetils = [{
        goodName: row.platformOrderDesc || '商品',
        goodSize: '默认规格',
        price: row.goodPrice || row.platformOrderPrice || 0,
        count: row.count || 1,
        realPrice: row.realPrice || row.platformOrderPrice || 0,
        goodsImage: '/default-product.png' // 使用默认图片
      }]
    } else {
      // 使用匹配到的商品信息，包含真实的goodsImage
      row.goodDetils = matchedGoods.map(good => ({
        goodName: good.goodsName || good.goodName || row.platformOrderDesc || '商品',
        goodSize: good.goodSize || good.spec || '默认规格',
        price: good.goodsPrice || good.price || row.goodPrice || row.platformOrderPrice || 0,
        count: row.count || 1,
        realPrice: row.realPrice || row.platformOrderPrice || 0,
        goodsImage: good.goodsImage || good.image || '/default-product.png' // 使用商品真实图片
      }))
    }
  }).catch(error => {
    console.error('获取商品信息失败:', error)
    // 出错时使用兜底数据
    row.goodDetils = [{
      goodName: row.platformOrderDesc || '商品',
      goodSize: '默认规格',
      price: row.goodPrice || row.platformOrderPrice || 0,
      count: row.count || 1,
      realPrice: row.realPrice || row.platformOrderPrice || 0,
      goodsImage: '/default-product.png'
    }]
  }).finally(() => {
    expandLoading[orderId] = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** tab切换事件处理 - 清除所有选中状态 */
function handleTabChange() {
  // 清除所有tab页面的选中状态
  selectedPlatformRow.value = null
  selectedNotShippedRow.value = null
  selectedShippedRow.value = null
  selectedCompletedRow.value = null
  selectedUnpaidRow.value = null
  selectedCanceledRow.value = null

  // 清除所有tab页面的选中ID
  selectedPlatformId.value = null
  selectedNotShippedId.value = null
  selectedShippedId.value = null
  selectedCompletedId.value = null
  selectedUnpaidId.value = null
  selectedCanceledId.value = null

  // 清除通用的选中状态
  ids.value = []
  single.value = true
  multiple.value = true
}

// 行点击选中处理函数（单选）
function handleSingleRowSelection(row, selectedId, selectedRow) {
  const orderId = row.orderId
  if (selectedId.value === orderId) {
    // 如果点击的是已选中的行，取消选中
    selectedId.value = null
    selectedRow.value = null
  } else {
    // 选中新行（自动取消之前的选中）
    selectedId.value = orderId
    selectedRow.value = row
  }
}

// 行点击事件 - 全部订单
function handleRowClick(row) {
  handleSingleRowSelection(row, selectedPlatformId, selectedPlatformRow)
  ids.value = selectedPlatformId.value ? [selectedPlatformId.value] : []
  single.value = selectedPlatformRow.value === null
  multiple.value = selectedPlatformRow.value === null
}

// 行点击事件 - 待发货订单
function handleNotShippedRowClick(row) {
  handleSingleRowSelection(row, selectedNotShippedId, selectedNotShippedRow)
}

// 行点击事件 - 已发货订单
function handleShippedRowClick(row) {
  handleSingleRowSelection(row, selectedShippedId, selectedShippedRow)
}

// 行点击事件 - 已完成订单
function handleCompletedRowClick(row) {
  handleSingleRowSelection(row, selectedCompletedId, selectedCompletedRow)
}

// 行点击事件 - 未支付订单
function handleUnpaidRowClick(row) {
  handleSingleRowSelection(row, selectedUnpaidId, selectedUnpaidRow)
}

// 行点击事件 - 已取消订单
function handleCanceledRowClick(row) {
  handleSingleRowSelection(row, selectedCanceledId, selectedCanceledRow)
}

// 获取行类名的函数（单选模式）
function getPlatformRowClassName({row}) {
  return selectedPlatformId.value === row.orderId ? 'selected-row' : ''
}

function getNotShippedRowClassName({row}) {
  return selectedNotShippedId.value === row.orderId ? 'selected-row' : ''
}

function getShippedRowClassName({row}) {
  return selectedShippedId.value === row.orderId ? 'selected-row' : ''
}

function getCompletedRowClassName({row}) {
  return selectedCompletedId.value === row.orderId ? 'selected-row' : ''
}

function getUnpaidRowClassName({row}) {
  return selectedUnpaidId.value === row.orderId ? 'selected-row' : ''
}

function getCanceledRowClassName({row}) {
  return selectedCanceledId.value === row.orderId ? 'selected-row' : ''
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单列表"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log('点击查看详情，行数据:', row);
  reset()
  const _orderId = row.orderId || ids.value
  console.log('订单ID:', _orderId);

  getPlatform(_orderId).then(response => {
    console.log('API响应:', response);
    form.value = response.data

    const orderData = response.data || row;
    console.log('准备传递的数据:', orderData);
    console.log('序列化后的数据:', JSON.stringify(orderData));

    router.push(
        {
          path: '/MallManagement/orderSet/orderDetail',
          query: {
            orderData: JSON.stringify(orderData)
          }
        }
    );
  }).catch(error => {
    console.error('获取订单详情失败:', error);
    // 如果API失败，使用行数据
    console.log('使用行数据作为备选:', row);
    router.push(
        {
          path: '/MallManagement/orderSet/orderDetail',
          query: {
            orderData: JSON.stringify(row)
          }
        }
    );
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认删除订单列表编号为"' + _orderIds + '"的数据项？').then(function () {
    return delPlatform(_orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  let selectedRow = null
  let fileName = 'platform'

  // 根据当前活动的tab页面获取选中的数据
  switch (activeName.value) {
    case 'first':
      selectedRow = selectedPlatformRow.value
      fileName = 'platform_all'
      break
    case 'second':
      selectedRow = selectedNotShippedRow.value
      fileName = 'platform_not_shipped'
      break
    case 'third':
      selectedRow = selectedShippedRow.value
      fileName = 'platform_shipped'
      break
    case 'fourth':
      selectedRow = selectedCompletedRow.value
      fileName = 'platform_completed'
      break
    case 'fifth':
      selectedRow = selectedUnpaidRow.value
      fileName = 'platform_unpaid'
      break
    case 'sixth':
      selectedRow = selectedCanceledRow.value
      fileName = 'platform_canceled'
      break
  }

  // 如果有选中的行，导出选中的数据
  if (selectedRow) {
    proxy.download('order/platform/export', {
      ...queryParams.value,
      orderIds: selectedRow.orderId
    }, `${fileName}_selected_${new Date().getTime()}.xlsx`)
  } else {
    // 如果没有选中的行，导出当前tab页面的所有数据
    let exportParams = {...queryParams.value}

    // 根据当前tab页面设置状态过滤条件
    switch (activeName.value) {
      case 'second':
        exportParams.status = 2 // 待发货
        break
      case 'third':
        exportParams.status = 3 // 已发货
        break
      case 'fourth':
        exportParams.status = 4 // 已完成
        break
      case 'fifth':
        exportParams.status = 1 // 未支付
        break
      case 'sixth':
        exportParams.status = 5 // 已取消
        break
        // 'first' 全部订单不需要额外过滤
    }

    proxy.download('order/platform/export', exportParams, `${fileName}_all_${new Date().getTime()}.xlsx`)
  }
}

getList()
</script>

<style scoped>
.goods-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
  margin: 0 auto;
}

/* 去掉表格标题行背景色 */
:deep(.el-table .el-table__header-wrapper .el-table__header thead th) {
  background-color: transparent !important;
}

/* 选中行样式 */
:deep(.el-table .selected-row) {
  background-color: #ecf5ff !important;
}

/* 选中行鼠标悬停效果 */
:deep(.el-table .selected-row:hover) {
  background-color: #d9ecff !important;
}

/* 未选中行鼠标悬停效果 */
:deep(.el-table .el-table__body tr:hover) {
  background-color: #f5f5f5 !important;
}

/* 行点击样式 - 添加鼠标指针 */
:deep(.el-table .el-table__body tr) {
  cursor: pointer;
}
</style>
